//
//  SettingViewController.m
//  JiuLe
//
//  Created by SunChao on 16/11/10.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "SettingViewController.h"
#import "ProtocolViewController.h"
#import "AboutViewController.h"
#import "MallRequestManager.h"
@interface SettingViewController ()<UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *cachLabel;
@property (weak, nonatomic) IBOutlet UISwitch *networkSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *tuiSongSwitch;
- (IBAction)TuiSongAction:(UISwitch *)sender;
- (IBAction)NetworkAction:(UISwitch *)sender;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    [self showNavgationWithLeftItemWithTitle:@"我的"];
    self.tableView.backgroundColor = RGB(239, 239, 244);
    self.cachLabel.text = [NSString stringWithFormat:@"当前缓存大小为:%.2f MB",[self filePath]];
    //获取推送状态
    
    NSString *pushStatus = [[NSUserDefaults standardUserDefaults] objectForKey:UserPush];
    NSLog(@"pushStatus:%@",pushStatus);
    if ([pushStatus isEqualToString:@"0"]) {
        self.tuiSongSwitch.on = NO;
    }else
    {
        self.tuiSongSwitch.on = YES;
    }
}
// 显示缓存大小
-( float )filePath
{
    
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    return [ self folderSizeAtPath :cachPath];
    
}
//1:首先我们计算一下 单个文件的大小

- ( long long ) fileSizeAtPath:( NSString *) filePath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if ([manager fileExistsAtPath :filePath]){
        
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
    }
    
    return 0 ;
    
}
//2:遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）

- ( float ) folderSizeAtPath:( NSString *) folderPath{
    
    NSFileManager * manager = [ NSFileManager defaultManager ];
    
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
    
    NSString * fileName;
    
    long long folderSize = 0 ;
    
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
        
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
        
    }
    
    return folderSize/( 1024.0 * 1024.0 );
    
}




// 清理缓存

- (void)clearFile
{
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    
    NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
    
    NSLog ( @"cachpath = %@" , cachPath);
    
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        
        NSString * path = [cachPath stringByAppendingPathComponent :p];
        
        if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
            
            [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
            
        }
        
    }
    
    [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
    
}
-(void)clearCachSuccess
{
    NSLog ( @" 清理成功 " );
     self.cachLabel.text = [NSString stringWithFormat:@"当前缓存大小为:%.2f MB",[self filePath]];
    [SVProgressHUD dismiss];

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}
- (void)setTuiSongBtnWithNewWorkError
{
    [self.tuiSongSwitch setOn:!(self.tuiSongSwitch.on)];
}

- (IBAction)TuiSongAction:(UISwitch *)sender {
    
        //接收推送
        NSMutableDictionary *params = [NSMutableDictionary new];
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
         [params setObject:userId forKey:@"user_id"];
        [MallRequestManager post:@"Notice/SetisPush" RequestParams:params  FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) {
                [SVProgressHUD showErrorWithStatus:@"请检查网络状态"];
                [self performSelectorOnMainThread:@selector(setTuiSongBtnWithNewWorkError) withObject:nil waitUntilDone:YES];
                return ;
            }
            id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([dic isKindOfClass:[NSDictionary class]]) {
                if ([[[dic objectForKey:@"status"]stringValue]isEqualToString:@"200"]) {
                    [SVProgressHUD showSuccessWithStatus:[dic objectForKey:@"message"]];
                    NSDictionary *result = [dic objectForKey:@"result"];
                    NSLog(@"%@",[[result objectForKey:@"ispush"]stringValue]);
                   
                    NSString *pushStatus = [[result objectForKey:@"ispush"]stringValue];
                   [[NSUserDefaults standardUserDefaults]setObject:pushStatus forKey:UserPush];
                    NSLog(@"------%@",[[NSUserDefaults standardUserDefaults]objectForKey:UserPush]);
                }
            }
            
        }];
}

- (IBAction)NetworkAction:(UISwitch *)sender {
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section ==0) {
        
    }else if (indexPath.section ==1)
    {
        if (indexPath.row ==1) {
            UIAlertView * alter=[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否清除缓存" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alter.delegate = self;
            [alter show];
            
        }else
        {
            
        }
    }else if (indexPath.section ==2)
    {
         [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8",kAPPID]]];
    }else if (indexPath.section ==3){
        if (indexPath.row ==0) {
            ProtocolViewController *protocol = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ProtocolViewController"];
            [self.navigationController pushViewController:protocol animated:YES];
        }else
        {
            AboutViewController *versionVC = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AboutViewController"];
            [self.navigationController pushViewController:versionVC animated:YES];
        }
    }
    
}
#pragma mark  --UIAlterViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex:%ld",(long)buttonIndex);
    
    if (buttonIndex ==1) {
        [SVProgressHUD showWithStatus:@"正在清理缓存"];
        [self clearFile];
    }
}
@end
